package com.template.tree;

import com.template.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author shenb
 * @date 2022-02-26 16:22
 */
public class _4_TreeTraversal2 {

  /** 前序遍历 */
  public static List<Integer> preOrder(TreeNode root) {
    List<Integer> integers = new ArrayList<>();

    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    while (!stack.isEmpty()) {
      TreeNode pop = stack.pop();
      integers.add(pop.val);

      if (pop.right != null) {
        stack.push(pop.right);
      }
      if (pop.left != null) {
        stack.push(pop.left);
      }
    }
    return integers;
  }

  /**
   * 辅助节点
   */
  public static TreeNode skip = new TreeNode(-1);

  /** 中序遍历 */
  public static List<Integer> midOrder(TreeNode root) {

    List<Integer> integers = new ArrayList<>();

    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    stack.push(skip);
    while (!stack.isEmpty()) {
      TreeNode pop = stack.pop();
      if (pop == skip) {
        TreeNode curRoot = stack.peek();
        if (curRoot.left != null) {
          stack.add(curRoot.left);
          stack.add(skip);
        }
      } else {
        integers.add(pop.val);

        if (pop.right != null) {
          stack.add(pop.right);
          stack.add(skip);
        }
      }
    }
    return integers;
  }

  /** 后序遍历 */
  public static List<Integer> postOrder(TreeNode root) {
    List<Integer> integers = new ArrayList<>();

    Stack<TreeNode> stack = new Stack<>();
    stack.push(root);
    stack.push(skip);
    while (!stack.isEmpty()) {
      TreeNode pop = stack.pop();
      if (pop == skip) {
        TreeNode curRoot = stack.peek();
        if (curRoot.right != null) {
          stack.add(curRoot.right);
          stack.add(skip);
        }

        if (curRoot.left != null) {
          stack.add(curRoot.left);
          stack.add(skip);
        }
      } else {
        integers.add(pop.val);
      }
    }
    return integers;
  }
}
